/**
 * 
 */
package com.easidea.tim.web.util.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.easidea.tim.action.ActionConstants;
import com.easidea.tim.web.util.annotation.NeedLoginCheck;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

/**
 * 从Context中检测当前context中是否包含有是否需要登录的标记，如果没有登录标记，则被认为系统错误
 * 若包含登录标记，且值为已登录，则表明当前用户已登录。若有标记但值为未登录，则当前用户未登录
 * 
 * @author Harrison
 *
 */
public class LoginCheckInterceptor implements Interceptor{
	
	 public static final String NEED_LOGIN = "need_login";

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void destroy() {}

	public void init() {}

	/**
	 * 
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		//判断当前访问的Action method 是否需要进行登录的判断
		//从session中提取用户数据
		//如果当前Action的method需要登录，且用户已登录，放行，否则跳转到登录页面
		
		 String methodName = invocation.getProxy().getMethod();
         Action action = (Action) invocation.getProxy().getAction();
         Method method = action.getClass().getMethod(methodName, new Class[]{});
         
         if (method.getAnnotation(NeedLoginCheck.class) != null){
        	 // 需要登录判断
        	 ActionContext ctx = ActionContext.getContext();
             HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
             HttpSession session = req.getSession();
             
             if (session.getAttribute(ActionConstants.LOGGED_USER) != null){
            	 return invocation.invoke();
             }else{
            	 return NEED_LOGIN;
             }
         }
         
		return invocation.invoke();
	}

}
